package com.future;

import com.future.util.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Description: 102. �������Ĳ������
 *
 * @Author: future
 * @Date:2022/5/24:0:28
 */
public class Solution_102 {

    public static void main(String[] args) {
        TreeNode head = new TreeNode(1);
        head.left = new TreeNode(2);
        head.right = new TreeNode(3);
        head.left.left = new TreeNode(4);
        head.left.right = new TreeNode(5);
        head.right.left = new TreeNode(6);
        head.right.right = new TreeNode(7);
        System.out.println(levelOrder(head));
    }

    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        if (root == null) {
            return ans;
        }
        TreeNode nextLevelNode = root.left != null ? root.left : root.right;
        List<Integer> tmp = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node == nextLevelNode) {
                ans.add(new ArrayList<Integer>() {{
                    addAll(tmp);
                }});
                // ���
                tmp.clear();
                nextLevelNode = node.left != null ? node.left : node.right;
            }
            if (node.left != null) {
                if (nextLevelNode == null) {
                    nextLevelNode = node.left;
                }
                queue.add(node.left);
            }
            if (node.right != null) {
                if (nextLevelNode == null) {
                    nextLevelNode = node.right;
                }
                queue.add(node.right);
            }
            tmp.add(node.val);
        }
        ans.add(tmp);
        return ans;
    }

}
